package com.zf.zfed.audit.set

import android.content.Intent
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.media.AudioManager
import android.content.Context
import android.provider.Settings
import android.view.WindowManager
import android.widget.Toast
import androidx.fragment.app.Fragment
import com.blankj.utilcode.util.FragmentUtils
import com.zf.zfed.audit.R
import com.zf.zfed.audit.base.TabContainer
import com.zf.zfed.audit.base.fragment.NavigationFragment
import com.zf.zfed.audit.data.ZFTabEnum
import com.zf.zfed.audit.databinding.FragmentSetListBinding
import com.zf.zfed.audit.set.about.AboutFragment
import com.zf.zfed.audit.set.HelpCenterFragment
import com.zf.zfed.audit.tools.extension.singleClick
import com.zf.zfed.audit.ui.Navigation
import com.zf.zfed.audit.ui.ZFHomeActivity
import com.zf.zfed.audit.ui.VolumeSlider
import com.zf.zfed.audit.ui.BrightnessSlider
import com.zf.zfed.audit.ui.DropdownSetItem
import com.zf.zfed.audit.ui.LoginManagementActivity
import com.zf.zfed.audit.data.ScreenTimeoutOptions
import com.zf.zfed.audit.database.ScreenTimeoutDatabase
import com.zf.zfed.base.BaseViewModeFragment

//class SetListFragment : AppCompatActivity() {
class SetListFragment : BaseViewModeFragment<FragmentSetListBinding>() {
        override fun onHiddenChanged(hidden: Boolean) {
        super.onHiddenChanged(hidden)
        if (!hidden) {
//            val result = LoginRepository.getCurrentUser()
//            if (result.isSuccess) {
//                result.getOrNull()?.let {
//                    var isAdmin = false
//                    it.roles.forEach { roleVO ->
//                        if ("admin" == roleVO.name) isAdmin = true
//                    }
//                    if (isAdmin) {
//                        binding.setItemLog.applyVisible()
//                        binding.setItemUser.applyVisible()
//                        binding.setItemConfig.applyVisible()
//                    }
//                }
//            }
        }
    }
    
    override fun initViews() {
        super.initViews()
        
        bind()
    }

    /**
     * 绑定数据
     *
     */
    private fun bind() {
        // 初始化音量控制
        initVolumeControl()
        
        // 初始化亮度控制
        initBrightnessControl()
        
        // 初始化熄屏设置
        initScreenTimeoutControl()
        
        // 登录管理按钮
        binding.setItemUsers.setOnClickListener {
            try {
                val intent = Intent(activity, LoginManagementActivity::class.java)
                startActivity(intent)
            } catch (e: Exception) {
                e.printStackTrace()
                Toast.makeText(requireContext(), "跳转登录管理失败: ${e.message}", Toast.LENGTH_SHORT).show()
            }
        }
        
        // 黑名单管理按钮
        binding.setItemBlack.setOnClickListener {
            try {
                val intent = Intent(activity, com.zf.zfed.audit.ui.BlacklistActivity::class.java)
                startActivity(intent)
            } catch (e: Exception) {
                e.printStackTrace()
                Toast.makeText(requireContext(), "跳转黑名单管理失败: ${e.message}", Toast.LENGTH_SHORT).show()
            }
        }
        
        binding.setItemWhite.setOnClickListener {
            try {
                val intent = Intent(activity, com.zf.zfed.audit.ui.WhitelistActivity::class.java)
                startActivity(intent)
            } catch (e: Exception) {
                e.printStackTrace()
                Toast.makeText(requireContext(), "跳转白名单管理失败: ${e.message}", Toast.LENGTH_SHORT).show()
            }
        }
        

        binding.setItemAbout.setOnClickListener {
            Toast.makeText(requireContext(), "点击了关于按钮", Toast.LENGTH_SHORT).show()
        }
        binding.setItemHelp.setOnClickListener {
            try {
                // 启动一个新的Activity来显示帮助中心
                val intent = Intent(activity, HelpCenterActivity::class.java)
                startActivity(intent)
            } catch (e: Exception) {
                e.printStackTrace()
                Toast.makeText(requireContext(), "跳转帮助中心失败: ${e.message}", Toast.LENGTH_SHORT).show()
            }
        }
    }
    
    /**
     * 初始化音量控制
     */
    private fun initVolumeControl() {
        val audioManager = requireContext().getSystemService(Context.AUDIO_SERVICE) as AudioManager
        
        // 获取当前系统音量
        val currentVolume = audioManager.getStreamVolume(AudioManager.STREAM_MUSIC)
        val maxVolume = audioManager.getStreamMaxVolume(AudioManager.STREAM_MUSIC)
        
        // 将系统音量转换为0-100的进度值
        val currentProgress = (currentVolume.toFloat() / maxVolume.toFloat()) * 100f
    }

    /**
     * 初始化亮度控制
     */
    private fun initBrightnessControl() {
        try {
            // 获取当前系统亮度
            val currentBrightness = Settings.System.getInt(
                requireContext().contentResolver,
                Settings.System.SCREEN_BRIGHTNESS,
                128 // 默认值
            )
            
            // 将系统亮度值(0-255)转换为0-100的进度值
            val currentProgress = (currentBrightness.toFloat() / 255f) * 100f
            
            // 设置初始亮度
            binding.setItemBrightness.setBrightness(currentProgress)
            
            // 设置亮度变化监听器
            binding.setItemBrightness.setOnBrightnessChangeListener(object : BrightnessSlider.OnBrightnessChangeListener {
                override fun onBrightnessChanged(brightness: Float) {
                    setBrightness(brightness)
                    
                    // 显示当前亮度百分比
                    val brightnessPercent = brightness.toInt()
//                    Toast.makeText(requireContext(), "亮度: $brightnessPercent%", Toast.LENGTH_SHORT).show()
                }
            })
        } catch (e: Exception) {
            Toast.makeText(requireContext(), "亮度控制初始化失败: ${e.message}", Toast.LENGTH_SHORT).show()
            e.printStackTrace()
        }
    }
    
    /**
     * 初始化熄屏设置控制
     */
    private fun initScreenTimeoutControl() {
        try {
            // 设置下拉选项
            binding.setItemSleep.setOptions(ScreenTimeoutOptions.getAllDisplayNames())
            
            // 设置选项变化监听器
            binding.setItemSleep.setOnOptionChangeListener { selectedOption ->
                // 获取对应的值
                val timeoutValue = ScreenTimeoutOptions.getValueByDisplayName(selectedOption)
                
                // TODO: 保存到数据库
                // val database = ScreenTimeoutDatabase(requireContext())
                // database.saveScreenTimeout(timeoutValue, selectedOption)
                
                // 显示选择结果
                Toast.makeText(requireContext(), "熄屏时间设置为: $selectedOption", Toast.LENGTH_SHORT).show()
                
                // TODO: 实际设置系统熄屏时间
                // setSystemScreenTimeout(timeoutValue)
            }
        } catch (e: Exception) {
            Toast.makeText(requireContext(), "熄屏设置初始化失败: ${e.message}", Toast.LENGTH_SHORT).show()
            e.printStackTrace()
        }
    }
    
    /**
     * 设置系统熄屏时间
     * TODO: 实现系统熄屏时间设置
     */
    private fun setSystemScreenTimeout(timeoutValue: Int) {
        try {
            if (timeoutValue == 0) {
                // 永不熄屏
                // TODO: 设置系统为永不熄屏
            } else {
                // 设置具体时间
                // TODO: 设置系统熄屏时间
            }
        } catch (e: Exception) {
            Toast.makeText(requireContext(), "设置熄屏时间失败: ${e.message}", Toast.LENGTH_SHORT).show()
            e.printStackTrace()
        }
    }
    
    /**
     * 设置系统亮度
     */
    private fun setBrightness(brightness: Float) {
        try {
            // 将0-100的进度值转换为系统亮度值(0-255)
            val systemBrightness = ((brightness / 100f) * 255f).toInt().coerceIn(1, 255)
            
            // 设置系统亮度
            Settings.System.putInt(
                requireContext().contentResolver,
                Settings.System.SCREEN_BRIGHTNESS,
                systemBrightness
            )
            
            // 立即应用到当前窗口
            val window = requireActivity().window
            val layoutParams = window.attributes
            layoutParams.screenBrightness = brightness / 100f
            window.attributes = layoutParams
            
        } catch (e: SecurityException) {
            Toast.makeText(requireContext(), "需要修改系统设置权限", Toast.LENGTH_LONG).show()
        } catch (e: Exception) {
            Toast.makeText(requireContext(), "设置亮度失败: ${e.message}", Toast.LENGTH_SHORT).show()
            e.printStackTrace()
        }
    }
}